// src/pages/WaterLogPage.tsx
import React, { useState, useEffect, useContext, useRef } from 'react';
import {
  IonPage,
  IonHeader,
  IonToolbar,
  IonTitle,
  IonContent,
  IonList,
  IonItem,
  IonLabel,
  IonInput,
  IonButton,
  IonIcon,
  IonCard,
  IonCardContent,
  IonCardHeader,
  IonCardTitle,
  IonDatetime,
  IonText,
  IonButtons,
  IonBackButton,
  IonGrid,
  IonRow,
  IonCol,
  useIonViewWillEnter
} from '@ionic/react';
import { waterOutline, addCircleOutline, trashOutline, water } from 'ionicons/icons';
// import { databaseService, WaterLog } from '../services/database';
import { format, parseISO } from 'date-fns';
import { zhCN } from 'date-fns/locale';

import './WaterPage.css'

import { SqliteServiceContext, StorageServiceContext } from '../App';
import { WaterLog } from '../models/WaterLog';
import { SQLiteDBConnection } from '@capacitor-community/sqlite';
import { Toast } from '@capacitor/toast';

import { platform } from '../App';


const WaterPage: React.FC = () => {
  const [amount, setAmount] = useState<number>(250); // 默认250ml
  const [logs, setLogs] = useState<WaterLog[]>([]);
  const [todayTotal, setTodayTotal] = useState<number>(0);
  const [date, setDate] = useState<string>(new Date().toISOString());


  const ref = useRef(false);
  const dbNameRef = useRef('');
  const isInitComplete = useRef(false);
  const [db, setDb] = useState<SQLiteDBConnection | null>(null);
  const sqliteServ = useContext(SqliteServiceContext);
  const storageServ = useContext(StorageServiceContext);

  const openDatabase = () => {
    try {
      const dbUsersName = storageServ.getDatabaseName();
      dbNameRef.current = dbUsersName;
      const version = storageServ.getDatabaseVersion();

      sqliteServ.openDatabase(dbUsersName, version, false).then((database) => {
        setDb(database);
        ref.current = true;
      });
    } catch (error) {
      const msg = `Error open database:: ${error}`;
      console.error(msg);
      Toast.show({
        text: `${msg}`,
        duration: 'long'
      });
    }
  }


  useIonViewWillEnter(() => {
    const initSubscription = storageServ.isInitCompleted.subscribe((value) => {
      isInitComplete.current = value;
      if (isInitComplete.current === true) {
        const dbUsersName = storageServ.getDatabaseName();
        if (ref.current === false) {
          if (platform === "web") {
            window.addEventListener('beforeunload', (event) => {

              sqliteServ.closeDatabase(dbNameRef.current, false).then(() => {
                ref.current = false;
              })
                .catch((error) => {
                  const msg = `Error close database:: ${error}`;
                  console.error(msg);
                  Toast.show({
                    text: `${msg}`,
                    duration: 'long'
                  });
                });
            });
            customElements.whenDefined('jeep-sqlite').then(() => {
              openDatabase();
            })
              .catch((error) => {
                const msg = `Error open database:: ${error}`;
                console.log(`msg`);
                Toast.show({
                  text: `${msg}`,
                  duration: 'long'
                });
              });

          } else {
            openDatabase();
          }
        }
      }
    });

    return () => {
      initSubscription.unsubscribe();
    };
  }, [storageServ]);



  // 加载喝水记录
  const loadWaterLogs = async () => {
    try {

      // 获取所有喝水记录
      const allLogs = await storageServ.getWaterRecords();
      console.log('所有喝水记录:', allLogs);
      // 按日期降序排序
      const sortedLogs = allLogs.sort((a, b) =>
        new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
      );

      setLogs(sortedLogs);

      // 计算今日总量
      const today = new Date().toISOString().split('T')[0];
      const todayLogs = allLogs.filter(log =>
        log.timestamp.startsWith(today)
      );

      const total = todayLogs.reduce((sum, log) => sum + log.amount, 0);
      setTodayTotal(total);
    } catch (error) {
      console.error('加载喝水记录失败:', error);
    }
  };

  // 初始化加载数据
  useEffect(() => {
    loadWaterLogs();
  }, []);

  // 添加喝水记录
  const addWaterLog = async () => {
    if (amount <= 0) {
      alert('请输入有效的饮水量');
      return;
    }

    const newLog: WaterLog = {
      id: 0,
      amount,
      timestamp: date
    };

    try {
      await storageServ.insertWaterLog(newLog);
      setAmount(250); // 重置为默认值
      setDate(new Date().toISOString()); // 重置为当前时间
      loadWaterLogs(); // 重新加载数据
    } catch (error) {
      console.error('添加喝水记录失败:', error);
      alert('添加记录失败，请重试');
    }
  };

  // 快捷添加喝水记录
  const quickAddWaterLog = async (quickAmount: number) => {
    const newLog: WaterLog = {
      id: 0,
      amount: quickAmount,
      timestamp: new Date().toISOString() // 使用当前时间
    };

    try {
      await storageServ.insertWaterLog(newLog);
      loadWaterLogs(); // 重新加载数据
    } catch (error) {
      console.error('dwj 添加喝水记录失败:', error);
      alert('添加记录失败，请重试');
    }
  };

  // 删除喝水记录
  const deleteWaterLog = async (id: number) => {
    try {
      await storageServ.deleteWaterLog(id);
      loadWaterLogs(); // 重新加载数据
    } catch (error) {
      console.error('删除喝水记录失败:', error);
      alert('删除记录失败，请重试');
    }
  };

  // 格式化时间显示
  const formatTime = (timestamp: string) => {
    return format(parseISO(timestamp), 'HH:mm', { locale: zhCN });
  };

  // 格式化日期显示
  const formatDate = (timestamp: string) => {
    const today = new Date().toISOString().split('T')[0];
    const logDate = timestamp.split('T')[0];

    if (today === logDate) {
      return '今天';
    }

    return format(parseISO(timestamp), 'MM/dd', { locale: zhCN });
  };

  return (
    <IonPage>
      <IonHeader>
        <IonToolbar color="primary">
          <IonButtons slot="start">
            <IonBackButton defaultHref="/home" />
          </IonButtons>
          <IonTitle>喝水记录</IonTitle>
        </IonToolbar>
      </IonHeader>

      <IonContent className="ion-padding">
        {/* 今日喝水统计 */}
        <IonCard color="light">
          <IonCardHeader>
            <IonCardTitle>
              <IonIcon icon={waterOutline} className="ion-margin-end" />
              今日喝水总量
            </IonCardTitle>
          </IonCardHeader>
          <IonCardContent className="ion-text-center">
            <IonText style={{ fontSize: '2.5rem', fontWeight: 'bold' }}>
              {todayTotal}
            </IonText>
            <IonText> ml</IonText>
            <IonText color="medium">
              <p>目标: 2000 ml</p>
            </IonText>
          </IonCardContent>
        </IonCard>

        {/* 快捷记录按钮 - 圆形设计 */}
        <IonCard>
          <IonCardHeader>
            <IonCardTitle>快速记录</IonCardTitle>
          </IonCardHeader>
          <IonCardContent>
            <div className="quick-buttons-container">
              <div className="quick-button" onClick={() => quickAddWaterLog(100)}>
                <div className="circle-button">
                  <IonIcon icon={water} className="button-icon" />
                </div>
                <IonLabel className="button-label">100ml</IonLabel>
              </div>

              <div className="quick-button" onClick={() => quickAddWaterLog(250)}>
                <div className="circle-button">
                  <IonIcon icon={water} className="button-icon" />
                </div>
                <IonLabel className="button-label">250ml</IonLabel>
              </div>

              <div className="quick-button" onClick={() => quickAddWaterLog(500)}>
                <div className="circle-button">
                  <IonIcon icon={water} className="button-icon" />
                </div>
                <IonLabel className="button-label">500ml</IonLabel>
              </div>
            </div>
          </IonCardContent>
        </IonCard>

        {/* 添加记录表单 */}
        <IonCard>
          <IonCardHeader>
            <IonCardTitle>自定义记录</IonCardTitle>
          </IonCardHeader>
          <IonCardContent>
            <IonItem>
              <IonLabel position="stacked">饮水量 (ml)</IonLabel>
              <IonInput
                type="number"
                value={amount}
                onIonChange={e => setAmount(parseInt(e.detail.value! || '0', 10))}
                min="1"
              />
            </IonItem>

            <IonButton
              expand="block"
              className="ion-margin-top"
              onClick={addWaterLog}
            >
              <IonIcon icon={addCircleOutline} slot="start" />
              添加记录
            </IonButton>
          </IonCardContent>
        </IonCard>

        {/* 历史记录列表 */}
        <IonList className="ion-margin-top">
          <IonItem lines="none">
            <IonLabel>
              <h2>喝水历史记录</h2>
            </IonLabel>
          </IonItem>

          {logs.length === 0 ? (
            <IonItem>
              <IonLabel className="ion-text-center">
                暂无记录，请添加喝水记录
              </IonLabel>
            </IonItem>
          ) : (
            logs.map(log => (
              <IonItem key={log.id}>
                <IonLabel>
                  <h2>{formatDate(log.timestamp)}</h2>
                  <p>{formatTime(log.timestamp)}</p>
                </IonLabel>
                <IonLabel slot="end" className="ion-text-right">
                  <h2>{log.amount} ml</h2>
                </IonLabel>
                <IonButton
                  slot="end"
                  fill="clear"
                  color="danger"
                  onClick={() => log.id && deleteWaterLog(log.id)}
                >
                  <IonIcon icon={trashOutline} />
                </IonButton>
              </IonItem>
            ))
          )}
        </IonList>
      </IonContent>


    </IonPage>
  );
};

export default WaterPage;